<?php
namespace App\Controllers\Experience;

use App\Libs\Base\Constant;
use App\Models\Goods\Goods;
use App\Models\Experience\ExpGoods;
use App\Models\Experience\ExpOrder;
use App\Models\Store\Store;
use App\Models\Peizhi\Peizhi;
use Phalcon\Validation;
use Phalcon\Validation\Validator\Regex as RegexValidator;



class CommitExpApply extends \App\Libs\Base\BaseAction
{
    protected function beforeRun()
    {
        parent::beforeRun();
       $this->needLogin = TRUE;
    }

    //用户体验商品的提交页面
    public function execute()
    {
        if ($this->request->isPost() == true) {
            //用户提交申请；
            if ($this->request->hasPost('apply_name') && $this->request->hasPost('apply_phone') && $this->request->hasPost('eid')) {
                $eid = $this->request->getPost('eid');
                $eGoods = ExpGoods::find([
                    'conditions' => 'id=?1 and show_status=2 and unix_timestamp(start_time)<?2 and unix_timestamp(end_time)>?2',
                    'bind' => [1 => $eid, 2 => time()]
                ]);

                if (!empty($eGoods)) {
                    if($eGoods->apply !='2'){
                        return \App\Libs\Views\Json::view(1, '来晚了，商品已经不允许体验了', null);
                    }

                    $apply_name = trim($this->request->getPost('apply_name'));
                    $apply_phone = trim($this->request->getPost('apply_phone'));
//                    $nameOk = preg_match(Constant::CHINESE_NAME, $apply_name);    $nameOk &&
                    $phoneOk = preg_match(Constant::MOBILE_REGREX, $apply_phone);
                    if (!( $phoneOk)) {
                        return \App\Libs\Views\Json::view(1, '用户提交信息不合法', null);
                    } else {
                        //todo：处理订单

                        $uid = $this->session->user->id;
//                  $uid = $this->request->getPost('uid');
                        $ifApplied = ExpOrder::find([
                            'conditions' => 'uid=?1 and eid=?2',
                            'columns' => 'uid,eid',
                            'bind' => [
                                1 => $uid,
                                2 => $eid
                            ]
                        ]);
                        if (!empty($ifApplied)) {
                            return \App\Libs\Views\Json::view(1, '您已经申请过体验此商品,无法继续申请!', null);
                        } else {
                            //查询申请的数量，进行数量限制
                            $haveApplyNum = ExpOrder::count([
                                'conditions' => 'eid=?1 and status=2',
                                'bind' => [1=>$eid]
                            ]);
                            if($haveApplyNum>=$eGoods->num){
                                return \App\Libs\Views\Json::view(1, '名额分配完了，下次早点来呦!', null);
                            }else{
                                //允许申请
                                //插入订单
                                $expOrder = new ExpOrder();
                                $result = $expOrder->create(array(
                                    'uid' => $uid,
                                    'eid' => $eid,
                                    'status' => 1,
                                    'linkman' => $apply_name,
                                    'ctime' => date('Y:m:d H:i:s'),
                                    'linkphone' => $apply_phone
                                ));
                                if ($result) {
                                    return \App\Libs\Views\Json::view(0, '申请成功', null);
                                } else {
                                    return \App\Libs\Views\Json::view(1, '服务器异常，请重试!', null);
                                }
                            }
                        }
                    }
                } else {
                    return \App\Libs\Views\Json::view(1, '体验商品不存在或已下架', null);
                }
            } else {
                return \App\Libs\Views\Json::view(1, '缺少参数', null);
            }
        } else {
            if ($this->request->has('eid')) {
                //查找商品的开始，结束时间
                $eDetail = ExpGoods::find([
                    'conditions' => 'id=?1',
                    'columns' => 'id as eid,gid,start_time,end_time,apply',
                    'bind' => [1 => $this->request->get('eid')]
                ])->toArray();
                if (empty($eDetail)) {
                    return \App\Libs\Views\Json::view(1, '指定的商品不存在', null);
                }
		//开始时间检测
                /**
		        if(strtotime($eDetail['start_time']) > time() ){
                    return \App\Libs\Views\Json::view(1, '客官莫急，体验开始时间还没有到呢！', null);
                }
		//结束时间检测
		        if(strtotime($eDetail['end_time']) < time() ){
                    return \App\Libs\Views\Json::view(1, '对不起，该体验商品已经下架了!', null);
                }
                 * **/

                //查找商品名字
                $goodsInfo = Goods::find([
                    'conditions' => 'id=?1',
                    'columns' => 'goods_name,sid',
                    'bind' => [1 => $eDetail['gid']],
                ])->toArray();
                $sid = $goodsInfo['sid'];
                $storeModel = Store::find([
                    'conditions' => 'id=?1',
                    'bind' => [1 => $sid]
                ]);

                $eDetail = array_merge($eDetail, $goodsInfo);
                $eDetail['store_address'] = $storeModel->store_address;
                $eDetail['st_time'] = date('m月d日 H:i ', strtotime($eDetail['start_time']));
                $eDetail['ed_time'] = date('m月d日 H:i ', strtotime($eDetail['end_time']));
                unset($eDetail['gid']);
                $matchTopImgUrl = Peizhi::find([
                    'type=16'
                ]);
                if(!empty($matchTopImgUrl)){
                    $eDetail['topImgUrl'] = $matchTopImgUrl->data;
                }else{
                    $eDetail['topImgUrl'] = 'https://clubbear.clubbear.cn/static/Index/images/shenqin.png';
                }
                return \App\Libs\Views\Json::view(0, '成功', $eDetail);
            } else {
                return \App\Libs\Views\Json::view(1, '请指定体验商品ID', null);
            }
        }
    }
}
